<?php 
class Solvex_Controller_Plugin_ViewSetup extends Zend_Controller_Plugin_Abstract
{
	/**
	 * Retrieve view
	 * 
	 * @return Solvex_View
	 */
	public function getView()
	{
		$viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
		return $viewRenderer->view;
	}

	public function preDispatch(Zend_Controller_Request_Abstract $request)
	{				
		$layout		= Zend_Layout::getMvcInstance();
		$view 		= $this->getView();
		$module		= $request->getModuleName();
		$controller = $request->getControllerName();
		$action		= $request->getActionName();
		$template   = Solvex::config('web/design/template');
		
		$view->originalModule 		= $module;
		$view->originalController	= $controller;
		$view->originalAction		= $action;
		
		$view->strictVars(true);
		$view->doctype('XHTML1_STRICT');
		$view->APP_SERVER_URL = $view->serverUrl() . $view->baseUrl();
		
		$templatesPackage = Solvex::config('system/package/templates');
		$templatesPath = APPLICATION_PATH . '/templates/' . $templatesPackage . '/' . $template;
		if(is_dir($templatesPath) && is_readable($templatesPath)){
			$layout->setLayoutPath($templatesPath . '/layouts');
			$view->addScriptPath($templatesPath . '/views');
		} else {
			throw new Solvex_Controller_Plugin_ViewSetup_Exception("Directory: $templatesPath is not readable or nonexistent.");
		}
		
		$assetsPackage = Solvex::config('system/package/assets');
		$assetsPath = PUBLIC_PATH . '/assets/' . $assetsPackage . '/' . $template;
		if(is_dir($assetsPath) && is_readable($assetsPath)){
			$resetCssFile = $assetsPath . '/' . $template . '/styles/reset.css';
			$defaultCssFile = $assetsPath . '/' . $template . '/styles/default.css';
			if(is_file($defaultCssFile) && is_readable($defaultCssFile)
				&& is_file($resetCssFile) && is_readable($resetCssFile)){
					$view->headLink()->appendStylesheet($resetCssFile)
									 ->appendStylesheet($defaultCssFile);
			} else {
				throw new Solvex_Controller_Plugin_ViewSetup_Exception("Reset/Default css files not available");
			}
		} else {
			throw new Solvex_Controller_Plugin_ViewSetup_Exception("Directory: $assetsPath is not readable or nonexistent.");
		}
		
	}
}